package com.thomasmoerman.dci3.pbc

import com.thomasmoerman.dci3.domain._
import com.thomasmoerman.dci3.frw._
import com.thomasmoerman.dci3.tmc._

trait Debtor {

  def payBills

}

trait DebtorProvider {
 
  implicit def asDebtor(person: Person): Debtor
  
}

import scala.collection.JavaConversions._

trait TransactionalDebtorProvider extends DebtorProvider {
  this: Transactional with PayBillsQueries with TransferMoneyContextFactory with HibernateSessionProvider =>
  
  implicit def asDebtor(person: Person): Debtor = new TransactionalDebtor(person)
  
  class TransactionalDebtor(self: Person) extends Debtor {
	   
	def payBills = inTransaction() {
	  findUnpaidBills(self).foreach(pay)
	  
	  session.merge(self.account)
	}
	
	def pay(bill: Bill) {
	  new TransferMoneyContext(Some(self.account), Some(bill.creditor.account), Some(bill.amount)).execute
	  
	  println("paid $" + bill.amount + " to " + bill.creditor.name + " for " + bill.comment)
	  
	  bill.markAsPaid
	}
	  
  }
  
}